<?php

namespace App\Repository;

use App\Entity\PageTag;
use App\Enum\RedisKeyEnum;
use App\Service\Redis;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method PageTag|null find($id, $lockMode = null, $lockVersion = null)
 * @method PageTag|null findOneBy(array $criteria, array $orderBy = null)
 * @method PageTag[]    findAll()
 * @method PageTag[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class PageTagRepository extends ServiceEntityRepository {
    private $redis;

    public function __construct (ManagerRegistry $registry, Redis $redis) {
        parent::__construct($registry, PageTag::class);
        $this->redis = $redis->redis;
    }

    /**
     * 获取类别数据，带缓存
     * @return array|mixed
     */
    public function findAllToArray () {
        $result = [];

        $redis_key = RedisKeyEnum::REDIS_PAGE_TAG_FIND_ALL_BY_ARRAY_KEY;
        $redis_page_tag_data = $this->redis->get($redis_key);
        if (is_null($redis_page_tag_data)) {
            $objs = $this->findAll();
            foreach ($objs as $obj) {
                $result[$obj->getId()] = $obj->getValue();
            }
            $this->redis->setex($redis_key, 600, serialize($result));
        } else {
            $result = unserialize($redis_page_tag_data);
        }

        return $result;
    }

    /**
     * 更新缓存
     */
    public function updateCache () {
        $result = [];
        $redis_key = RedisKeyEnum::REDIS_PAGE_TAG_FIND_ALL_BY_ARRAY_KEY;
        $objs = $this->findAll();
        foreach ($objs as $obj) {
            $result[$obj->getId()] = $obj->getValue();
        }
        $this->redis->setex($redis_key, 600, serialize($result));
    }

    /**
     * 获取所有标签ID
     * @return array
     */
    public function getIds () {
        $result = [];

        $items = self::findAll();
        foreach ($items as $item) {
            array_push($result, $item->getId());
        }

        return $result;
    }

    /**
     * 根据ids获取标签
     * @param $tags
     * @return mixed
     */
    public function getTags ($tags) {
        return $this->createQueryBuilder('t')
            ->select('t.value')
            ->andWhere('t.id IN ('.implode(',', $tags).')')
            ->getQuery()
            ->getResult();
    }
}
